import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class PerformanceIssueComputePage extends StatefulWidget {
  const PerformanceIssueComputePage({super.key});

  @override
  State<PerformanceIssueComputePage> createState() =>
      _PerformanceIssueComputePageState();
}

class _PerformanceIssueComputePageState
    extends State<PerformanceIssueComputePage> {
  bool isProcessing = false;

  // 使用 compute 将任务移到后台执行
  Future<void> _simulateLongTask() async {
    setState(() {
      isProcessing = true;
    });

    // 将耗时任务移到后台线程执行
    await compute(heavyComputation, 1000000000);

    setState(() {
      isProcessing = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('卡顿模拟'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            isProcessing
                ? const CircularProgressIndicator()
                : const SizedBox.shrink(),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: isProcessing ? null : _simulateLongTask,
              child: const Text('开始长时间任务'),
            ),
          ],
        ),
      ),
    );
  }
}

// 模拟耗时的计算
int heavyComputation(int count) {
  for (int i = 0; i < count; i++) {
    // 模拟复杂计算
  }
  return count;
}
